//index.js
//获取应用实例
const app = getApp()
let config = require('../../config/config.js')
let request = require('../../utils/request.js')
let QQMapWx = require('../../utils/qqmap-wx-jssdk.js')
let qqmapsdk = new QQMapWx({ key: config.map_key })

Page({
  data: {
    barHeight: wx.getMenuButtonBoundingClientRect().bottom,
    pageHeight: app.globalData.pageHeight,
    paddingTop: app.globalData.paddingTop,
    changeParkingDialog: false,
    handrailDialog: false,
    parkInfo: {},
    parkingOwnerData: {},
    parkList: [],
    parkName: '',
    parkId: '',
    parkSource: '',
    aisleList: [],
    selectAisleData: {},
    showCustParkTicket: -1,
    userId: null,
    username: null,
    phoneNumber: null,
    shopId: null,
    managerName: null,
    telephone: null,
    shopName: null,
    todayRevenue: 0,
    checkDate: 1,
    writeOffRevenue: 0,
    LinkIndexMax: 0,
    LinkIndexMin: 0,
    dialogShow: false,
    writeOffContent: null,
    orderCode: null,
    writeOffRecord: [],
    searchRecordCode: null,
    shopList: [],
    investAmount: 0,
    chart: null,
    buyTicketDialog: false,
    parkInfoDialog: false,
    markerPark: null,
    // mapKey: config.map_key,
    infoDialog:false,
    parkingShow:false,   //获取平台停车劵
    parkingList:[],
    isShopkeeper:null,
  },
  
  onLoad: function () {
    console.log('右上角的胶囊按钮的信息：', this.data.barHeight)
    this.setData({
      isShopkeeper:wx.getStorageSync('isShopkeeper')
    })
  },
  onReady: function () {
    

    //  创建地图
    this.MapContext = wx.createMapContext('myMap');
  },
  onShow() { 
    
    this.setData({
      userId: wx.getStorageSync('shop_manager_id'),
      username: wx.getStorageSync('username'),
      phoneNumber: wx.getStorageSync('phoneNumber')
    })
    
     // 获取用户当前位置
    this.getLocation()
    //  根据用户ID查询店铺
    this.getShopByManageId(this.data.userId)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.hideParking()
  },
      /**
   * 获取停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getParks(longitude, latitude) {
    request.http(
      '/park/park-info/getParkList', 
      'GET'
    ).then((res) => {
      if (res.data.code == 200) {
        let parkList = res.data.data;
        let markers = [];

        //  停车场位置marker
        for (let i = 0; i < parkList.length; i++) {
          let marker = this.getMarker(i + 1, parkList[i].longitude, parkList[i].latitude, 'https://mis.lmtc.zmzncs.com/file/WeChat/shop-point-icon.png', 22, 29)
          markers.push(marker);
        }
        //  车主位置marker
        let myMarker = this.getMarker(0, longitude, latitude, 'https://mis.lmtc.zmzncs.com/file/WeChat/shop-location.png', 26, 34)
        markers.unshift(myMarker);  //  数组头部插入

        this.setData({ parkList: parkList, markers: markers })

        //  移动到我的位置
        if (longitude !== 0 && latitude !== 0) {
          this.MapContext.moveToLocation({ longitude, latitude })
        }
      }

      //  车主位置实时监听
      this.locationChange()
    }).catch(err => { console.error(err) })
  },
    /**
   * 点击地图上的标记
   */
  checkMarkerPark(e) {
    console.log('点击地图上的标记：', e)

    // if (this.data.parkInfoDialog) { return }
    if (e.detail.markerId == 0) {
      wx.showToast({ title: '这是您当前位置', icon: 'none' });
      this.setData({ parkInfoDialog: false })
      return
    }

    //  停车场marker
    let marker = this.data.parkList[e.detail.markerId - 1];
    console.log('停车场marker：', marker)
    this.MapContext.moveToLocation({ longitude: marker.longitude, latitude: marker.latitude })

    //  获取停车场信息
    request.http(
      '/park/park-info/get-by-id', 
      'GET', 
      { id: marker.id }
    ).then(parkRes => {
      console.log('停车场信息：', parkRes)
      let data = parkRes.data
      if (data.code == 200) {
        let parkInfo = data.data
        this.setData({ markerPark: parkInfo, parkInfoDialog: true })
      }
    })
  },
  /**
   * 获取客户待激活、已激活停车券
   */
  // getCustParkTicket() {
  //   console.log('获取客户待激活、已激活停车券')
  //   //  待激活停车券
  //   if(this.data.showCustParkTicket == 2){
  //     this.selectComponent('#not-activation').getCustParkTicket(this.data.showCustParkTicket)
  //   }
  //   //  已激活停车券
  //   if(this.data.showCustParkTicket == 0){
  //     this.selectComponent('#activated').getCustParkTicket(this.data.showCustParkTicket)
  //   }
  // },
    /**
   * 切换客户待激活、已激活停车券
   */
  switchCustParkTicket(e) {
    this.setData({ showCustParkTicket: e.currentTarget.dataset.status })
  },
    /**
   * 根据用户ID查询店铺
   */
  getShopByManageId(id) {
    request.http('/shop/shop-info/get-by-manage-id', 'GET', { manageId: id })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let shopId = wx.getStorageSync('shopId')
          let hasCacheShop = false
          //  登录用户是否有缓存店铺
          if(shopId != null && shopId != ''){
            data.data.forEach((shop,index)=> {
              if(shop.id == shopId){  
                hasCacheShop = true; 
                wx.setStorageSync('shopName', shop.shopName) 
                wx.setStorageSync('shopId', shop.id) 
                wx.setStorageSync('username', shop.username) 
                wx.setStorageSync('telephone', shop.telephone)
              }
            })
          }
          this.setData({
            shopName: hasCacheShop == true ? wx.getStorageSync('shopName') : data.data[0].shopName,
            shopId: hasCacheShop == true ? wx.getStorageSync('shopId') : data.data[0].id,
            managerName: hasCacheShop == true ? wx.getStorageSync('username') : data.data[0].username,
            telephone: hasCacheShop == true ?  wx.getStorageSync('telephone') : data.data[0].telephone,
            shopList: data.data,
            showCustParkTicket: 2 
          })
          wx.setStorageSync('shopName', this.data.shopName) 
          wx.setStorageSync('shopId', this.data.shopId) 
          wx.setStorageSync('username', this.data.managerName) 
          wx.setStorageSync('telephone', this.data.telephone)

          this.parkingList()

          //  获取客户待激活、已激活停车券
          // this.getCustParkTicket()
        }
      })
  },
  //跳转展示 店铺审核列表
  storeAudit(){
    wx.navigateTo({url: '../storeAudit/storeAudit'})
  },
  /**
   * 手动激活
   */
  manualWriteOff() {
    this.setData({ dialogShow: true })
  },
  /**
   * 扫码
   */
  scanCode() {
    let _this = this
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let data = res.result
        _this.setData({
          dialogShow: true,
          orderCode: data
        })
        //  获取激活码信息
        _this.getByTicketCode(data);
      }
    })
  },
    /**
   * 根据激活码查询停车券信息
   */
  getByTicketCode(e) {
    let code = e.detail ? e.detail.value : e
    if(code.length == 16){
      request.http(
        '/customer/cust-ticket/get-by-ticket-code', 
        'GET', 
        { ticketCode: code, shopId: this.data.shopId }
      ).then(res => {
        let data = res.data
        console.log('激活码信息：', data)
        if (data.code == 200) {
          this.setData({ writeOffContent: data.data })
        }
      })
    }
  },
  /**
   * 确认激活
   */
  submit(id) {
    console.log('商户id：', this.data.shopId)
    if(this.data.writeOffContent == null || this.data.writeOffContent.id == null){
      wx.showToast({ icon: 'none', title: '激活码错误' })
      return
    };
    let _this = this;
    request.http(
      '/customer/cust-ticket/activate-ticket', 
      'POST', 
      { id: this.data.writeOffContent.id, shopId: this.data.shopId }
    ).then(res => {
      let data = res.data
      if(data.code == 200) {
        wx.showToast({
          title: '激活成功',
          duration: 2000,
          success:function(){
            setTimeout(function () {
              _this.setData({
                dialogShow: false,
                writeOffContent: {},
                orderCode: ''
              })
            }, 2000) 
          }
        })
        //  根据用户ID查询店铺     目前打开这段代码后 上面的激活成功提示就会消失
        // this.getShopByManageId(this.data.userId)
      }
    })
  },
  /**
   * 获取激活记录订单号
   */
  searchRecord(e) {
    this.setData({ searchRecordCode: e.detail.value  })
  },
  /**
   * 更换店铺
   */
  changeShop() {
    this.setData({ changeParkingDialog: true })
  },
  // 关闭店铺
  storeShutDown(){
    this.setData({ changeParkingDialog: false })
  },
  /**
   * 选择店铺
   */
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.getShopById(e.detail.value)
    this.setData({ changeParkingDialog: false })
  },
  //跳转添加店铺页面
  tozc(){
    let info = this.data.shopList[0];
    let data = {
      telephone:info.telephone,
      username:info.username
    }
    wx.navigateTo({  url: '../register/register?data='+JSON.stringify(data)})
  },
  /**
   * 获取商户
   */
  getShopById(id){
    request.http('/shop/shop-info/get-by-id', 'Get', { id: id })
      .then(res => {
        console.log('获取商户信息：', res)
        let data = res.data
        if (data.code == 200) {
          this.setData({
            shopName: data.data.shopName,
            shopId: data.data.id,
            managerName: data.data.username,
            telephone: data.data.telephone,
            showCustParkTicket: 2 
          })
          wx.setStorageSync('shopName', this.data.shopName) 
          wx.setStorageSync('shopId', this.data.shopId) 
          wx.setStorageSync('managerName', this.data.username) 
          wx.setStorageSync('telephone', this.data.telephone) 
          this.parkingList()
          //  获取客户待激活、已激活停车券
          // this.getCustParkTicket()
        }
      })
  },
  /**
   * 购买停车券
   */
  showBuyParkTicketDialog(){
    this.setData({ buyTicketDialog: true })
  },
  /**
   * 获取用户当前位置
  */
  getLocation() {
    return new Promise((resolve, reject) => {
      let _this = this
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          console.log('获取用户当前位置成功', res)
          _this.setData({ longitude: res.longitude, latitude: res.latitude, hasmarkers: true })
          //  获取停车场
          _this.getParks(res.longitude, res.latitude)

          resolve(res)
        },
        fail(err) {
          console.error('获取当前位置失败：', err.errMsg)
          // wx.showToast({ title: '获取当前位置失败', icon: 'none' })
          //  如果未允许定位，则跳转定位设置页面
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting['scope.userLocation']) {
                _this.openUserLocation()
              }
            }
          })
          
          reject(err)
        }
      })
    })
  },
    /**
   * 获取marker
   */
  getMarker(id, longitude, latitude, iconPath, width, height) {
    return { id: id, longitude: longitude, latitude: latitude, iconPath: iconPath, width: width, height: height, zIndex: 1400 }
  },
  /**
   * 开启定位
   */
  openUserLocation() {
    let _this = this
    wx.showModal({
      content: '请您先授权位置信息',
      confirmText: '去授权',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.openSetting({
            withSubscriptions: true,
            success(locationRes) {
              _this.setData( { isLocalLocation: true } )
              wx.setStorageSync('isLocalLocation', locationRes.authSetting['scope.userLocation'])
            }
          })
        }
      }
    })
  },
  /**
   * 车主位置实时监听
   */
  locationChange() {
    wx.startLocationUpdate({
      success: (res) => {
        wx.onLocationChange((result) => {
          var markers = this.data.markers
          for (var item of markers) {
            if (!item) { continue }
            //  车主位置marker
            if (item.id == 0) {
              item.latitude = result.latitude
              item.longitude = result.longitude
            }
          }
          this.setData({ markers: markers })
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  /**
   * 关闭弹窗
   */
  closeDialog() {
    this.setData({ 
      infoDialog: false,
      parkInfoDialog: false,
      dialogShow: false    //激活码的 弹框状态
    })
  },
  /**
   * 当没有可用的配置引流券时，关闭底部引流卷弹框 并且，打开购买引流卷弹框。
   */
  modify(){
    this.setData({ parkInfoDialog: false })   //关闭配置引流卷
    this.setData({ buyTicketDialog: true })   //打开购买引流卷
  },

   /**
   * 关闭发放的引流劵弹窗
   */
 
  /**
   * 关闭发放的引流劵弹窗
   */
  securities(){
    wx.navigateTo({  url: '../securities/securities' })
  },

  //隐藏弹框，平台发放的停车券
  closeParkingShow(){
    this.setData({
      parkingShow:false
    })
    this.hideParking()
  },
  //首页提醒的停车券
  parkingList(){
    request.http(
      '/shop/park-ticket-buy-record/getTipsParkTicket', 
      'POST', 
      {shopId:wx.getStorageSync('shopId')},
    ).then(res => {
      console.log(res)
      let data = res.data
      if (data.code == 200) {
        if(data.data.length != 0){
          this.setData({
            parkingShow:true,
            parkingList:data.data
          })
        }
      }
    })
  },
  //跳转查看  停车劵。我的卡卷页面
  toParking(){
    wx.navigateTo({
      url: '/pages/mine/mine',
    })
  },

  //页面隐藏后   调取确认接口，为了只能第一次显示 获得停车劵弹框
  hideParking(){
    request.http(
      '/shop/park-ticket-buy-record/updateTipsStatus', 
      'POST', 
      {shopId:wx.getStorageSync('shopId')},
    ).then(res => {
      console.log(res)
      let data = res.data
      if (data.code == 200) {
        this.setData({
          parkingShow:false
        })
      }
    })
  },
//使用说明
  illustrate(){
    wx.navigateTo({
      url: '/pages/illustrate/illustrate',
    })
  },
})
